<template>
    <div v-loading="loading" style="width: 100%;">
        <SavePage :title="setTitle">
            <template slot="buttons">
                <BaseButton :loading="btnLoading" @click="submit()">保存</BaseButton>
            </template>
            <template slot="body">
                <TitleTips title="基本信息" :required="true" />
                <el-form ref="form" :model="form" class="size-auto" :rules="rules" :inline="true" size="medium" label-width="86px">
                    <el-row :gutter="24">
                        <el-col :xl="6" :lg="8">
                            <el-form-item label="负责人" prop="principal">
                                <el-input v-if="type === 'change' || !!change" v-model="form.principalName" disabled />
                                <el-select v-else v-model="form.principal" placeholder="请选择">
                                    <el-option
                                        v-for="item in userOptions"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value"
                                    />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :xl="6" :lg="8">
                            <el-form-item label="上级批复" prop="higherPrincipal">
                                <el-input v-if="type === 'change' || !!change" v-model="form.higherPrincipalName" disabled />
                                <el-select v-else v-model="form.higherPrincipal" placeholder="请选择">
                                    <el-option
                                        v-for="item in superLevelUserOptions"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value"
                                    />
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>             
                </el-form>
                <FormItem ref="formItem" :form="form.contentList" :type="type" :query="itemQuery" :plan-type="form.planType" :loading.sync="loading" />
            </template>
        </SavePage>
    </div>
</template>

<script>
import { BudgetingOldModel, RoadPlanModel, RoadModel } from '@/models' 
import FormItem from './components/FormItem'
import { uniqueId } from 'lodash-es'
import approverUser from '../../../mixins/approver-user'

export default {
    name: 'StandingBookAdd',
    components: {
        FormItem
    },
    mixins: [approverUser],
    data() {
        return {
            loading: false,
            model: new RoadPlanModel(),
            budgetingModel: new BudgetingOldModel(),
            roadModel: new RoadModel(),
            form: {
                roadCode: null,
                tabulation: null,
                principal: null,
                higherPrincipal: null,
                planType: 1, // 计划类型 1-年度计划，2-季度计划，3-月度计划
                recordType: 1 // 记录类型 1-计划，2-变更 （默认为1）
            },
            rules: {
                principal: [{ required: true, message: '请选择负责人', trigger: 'change' }],
                higherPrincipal: [{ required: true, message: '请选择上级批复', trigger: 'change' }]
            },
            defalutUserId: null,
            number: null,
            type: 'add',
            typeName: '新建',
            btnLoading: false,
            change: null,
            itemQuery: {}
        }
    },
    computed: {
        workProject() {
            // 在组件上绑定了该属性但子组件没接收，目的是为了让计算属性生效
            let workProject = this.$store.getters.types.workProject || []
            workProject = workProject.map(item => {
                return {
                    value: item.id,
                    label: item.name,
                    uid: uniqueId()
                }
            })
            this.$set(this.everydayFormItems[4], 'options', workProject)
            return workProject
        },
        setTitle() {
            let title = ''
            if (this.form.month) {
                title = `${this.typeName}${this.form.year}年${this.form.month}月份${this.form.highwayName}养护计划`
            } else if (this.form.quarter) {
                title = `${this.typeName}${this.form.year}年${this.form.quarter}季度${this.form.highwayName}养护计划`
            } else {
                title = `${this.typeName}${this.form.year}年度${this.form.highwayName}养护计划`
            }
            return title
        }
    },
    async created() {
        this.getTypes()
        
        this.getQuery()
        if (this.type === 'change' || this.type === 'edit') {
            await this.getEditDetail()
        }
        
        // 混淆approverUser里的2个方法
        this.getUserByOrg(this.defalutUserId || this.form.tabulation)
        this.getSuperLevelUser(this.defalutUserId || this.form.tabulation)
    },
    methods: {
        getTypes() {
            this.$store.dispatch('types/query', ['workProject'])
        },
        // 获取编辑时需要的详情数据
        getEditDetail() {
            return this.model.getEditDetail({ number: this.number }).then(res => {
                // 如果是变更，列表数据要置空，重新填写
                if (this.type === 'change') { res.contentList = [] }
                this.form = res
            })
        },
        getQuery() {
            this.loading = true
            this.type = this.$route.query.type
            this.number = this.$route.query.number
            this.form.number = this.number
            this.form.planType = Number(this.$route.query.planType)
            if (this.type === 'edit') {
                this.typeName = '编辑'                
                this.recordType = this.$route.query.recordType || null
                // 变更的编辑页需要获取下change参数
                this.change = this.$route.query.change || false
            } else if (this.type === 'add') {
                this.typeName = '新建'
                // 新增时，当前用户默认为制表人
                this.defalutUserId = this.$store.getters.avatar.id
                this.form.year = this.$route.query.year
                this.form.quarter = this.$route.query.quarter
                this.form.month = this.$route.query.month

                const road = JSON.parse(decodeURIComponent(this.$route.query.road))
                this.form = Object.assign(this.form, road)
            } else if (this.type === 'change') {
                this.typeName = '变更'
                this.recordType = this.$route.query.recordType || null
            }
            // 用于formItem查询预算信息使用
            this.itemQuery = {
                roadCode: this.form.roadCode || this.$route.query.roadCode,
                year: this.form.year || this.$route.query.year,
                quarter: this.form.quarter || this.$route.query.quarter,
                month: this.form.month || this.$route.query.month
            }
        },
        getDetail() {
            // planType:计划类型 1-年度，2-季度，3-月度，当前页为年度的写死为1
            return this.model.detail({ number: this.number, planType: 1 }).then(res => {
                this.form = res
            })
        },
        submit() {
            this.btnLoading = true
            this.$refs['form'].validate(async valid => {
                if (valid) {
                    const res = await this.$refs['formItem'].handleValidate()
                    if (res) {
                        const form = JSON.parse(JSON.stringify(this.form))
                        // 如果是变更，这个是年度计划，添加planType为1，加上当前变更changeId，删除原id
                        if (this.type === 'change') {
                            form.planType = 1
                            form.changeId = form.id
                            delete form.id
                        }
                        const data = {
                            ...form,
                            contentList: this.$refs['formItem'].list
                        }
                        this.model.saveOrUpdate(data).then(() => {
                            this.$message({
                                type: 'success',
                                message: this.type === 'edit' ? '修改成功！' : '新建成功！',
                                duration: 500,
                                onClose: () => {
                                    this.$router.go(-1)
                                }
                            })
                        }).finally(() => {
                            this.btnLoading = false
                        })
                    } else {
                        this.btnLoading = false
                    }
                } else {
                    this.btnLoading = false
                }
            })
        }
    }
}
</script>

<style lang="scss" scoped>
.el-form--inline.size-auto.width-100 {
    ::v-deep {
        // form的label-width：72px 根据实际label宽度修改
        .el-form-item__content {
            width: calc(100% - 100px);
        }
    }    
}
.margin-b-0 {
    margin-bottom: 0;
}
</style>
